<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      body {
        height: 2000px;
      }
      div {
        position: absolute;
        width: 100px;
        height: 100px;
        background-color: red;
        cursor: pointer;
      }
    </style>
  </head>
  <body>
    <div></div>
    <script>
      //onmousedown  onmousemove   onmouseup
      var dragItem = document.querySelector("div");
      dragItem.style.left = window.sessionStorage.getItem("left") || 0;
      dragItem.style.top = window.sessionStorage.getItem("top") || 0;
      dragItem.addEventListener("mousedown", downHandler);
      function downHandler(e) {
        var x = e.offsetX;
        var y = e.offsetY;

        document.addEventListener("mousemove", moveHandler);
        document.addEventListener("mouseup", upHandler);

        function moveHandler(e) {
          var l = e.pageX - x;
          var t = e.pageY - y;
          dragItem.style.left = l + "px";
          dragItem.style.top = t + "px";
        }
        function upHandler() {
          document.removeEventListener("mousemove", moveHandler);
          window.sessionStorage.setItem("left", dragItem.style.left);
          9;
          window.sessionStorage.setItem("top", dragItem.style.top);
        }
      }
    </script>
  </body>
</html>
